#include "./../inc/main.h"
#include "./../inc/chessGames.h"
#include "./../inc/ai_strategy.h"

// 简单AI：随机选择合法走法
Move EasyAIStrategy::makeMove(const ChessGame &game)
{
    static bool seeded = false;
    if (!seeded)
    {
        srand(time(nullptr));
        seeded = true;
    }

    // 获取所有黑方棋子的合法走法
    vector<Move> validMoves;
    const auto &board = game.getBoard();

    for (int x = 0; x < BOARD_COLS; ++x)
    {
        for (int y = 0; y < BOARD_ROWS; ++y)
        {
            // 添加空指针检查
            if (board[x][y] && board[x][y]->getPieceColor() == Black)
            {
                // 检查所有可能的目标位置
                for (int tx = 0; tx < BOARD_COLS; ++tx)
                {
                    for (int ty = 0; ty < BOARD_ROWS; ++ty)
                    {
                        // 确保不是原地移动，并且目标位置没有己方棋子，移动是合法的
                        if ((tx != x || ty != y) &&
                            !(board[tx][ty] && board[tx][ty]->getPieceColor() == Black) &&
                            board[x][y]->canMoveTo(Point(tx, ty), board))
                        {
                            validMoves.emplace_back(Point(x, y), Point(tx, ty));
                        }
                    }
                }
            }
        }
    }
    // 随机选择一个走法
    if (!validMoves.empty())
    {
        int idx = rand() % validMoves.size();
        return validMoves[idx];
    }

    // 理论上不会走到这里
    return Move(Point(-1, -1), Point(-1, -1));
}

// 困难AI：极大极小值算法实现（带Alpha-Beta剪枝）
Move HardAIStrategy::makeMove(const ChessGame &game)
{
    vector<Move> validMoves = getAllValidMoves(game, Black);
    cout << "困难AI找到 " << validMoves.size() << " 个合法移动" << endl;

    if (validMoves.empty())
    {
        cout << "困难AI没有合法移动可选" << endl;
        return Move(Point(-1, -1), Point(-1, -1));
    }

    int bestScore = INT_MIN;
    Move bestMove = validMoves[0];

    // 搜索深度降低到2以提高速度
    for (const auto &move : validMoves)
    {
        // 创建临时游戏状态进行模拟
        ChessGame tempGame(game);
        if (tempGame.simulateMove(move.from.x(), move.from.y(), move.to.x(), move.to.y()))
        {
            int score = minimax(tempGame, 2, false, INT_MIN, INT_MAX); // Alpha-Beta剪枝
            if (score > bestScore)
            {
                bestScore = score;
                bestMove = move;
            }
        }
    }

    cout << "困难AI选择移动: 从(" << bestMove.from.x() << "," << bestMove.from.y()
         << ") 到 (" << bestMove.to.x() << "," << bestMove.to.y() << ")" << endl;
    return bestMove;
}

// 评估函数：根据棋子价值和位置打分
int HardAIStrategy::evaluateBoard(const ChessGame &game)
{
    const auto &board = game.getBoard();
    int score = 0;

    // 棋子基础价值表
    map<PieceType, int> pieceValues = {
        {King, 10000},
        {Advisor, 200},
        {Elephant, 200},
        {Horse, 400},
        {Chariot, 900},
        {Cannon, 450},
        {Pawn, 100}};

    for (int x = 0; x < BOARD_COLS; ++x)
    {
        for (int y = 0; y < BOARD_ROWS; ++y)
        {
            if (board[x][y])
            {
                int value = pieceValues[board[x][y]->getType()];
                // 黑方为正分，红方为负分
                if (board[x][y]->getPieceColor() == Black)
                {
                    score += value;
                }
                else
                {
                    score -= value;
                }
            }
        }
    }

    return score;
}

// 极大极小值递归搜索（带Alpha-Beta剪枝）
int HardAIStrategy::minimax(ChessGame game, int depth, bool isMaximizingPlayer, int alpha, int beta)
{
    if (depth == 0 || game.isGameOver())
    {
        return evaluateBoard(game);
    }

    vector<Move> validMoves = getAllValidMoves(
        game, isMaximizingPlayer ? Black : Red);

    if (validMoves.empty())
    {
        return evaluateBoard(game);
    }

    if (isMaximizingPlayer)
    {
        int maxScore = INT_MIN;
        for (const auto &move : validMoves)
        {
            ChessGame tempGame = game;
            if (tempGame.simulateMove(move.from.x(), move.from.y(), move.to.x(), move.to.y()))
            {
                int score = minimax(tempGame, depth - 1, false, alpha, beta);
                maxScore = max(maxScore, score);
                alpha = max(alpha, score);
                // Alpha-Beta剪枝
                if (beta <= alpha)
                    break;
            }
        }
        return maxScore;
    }
    else
    {
        int minScore = INT_MAX;
        for (const auto &move : validMoves)
        {
            ChessGame tempGame = game;
            if (tempGame.simulateMove(move.from.x(), move.from.y(), move.to.x(), move.to.y()))
            {
                int score = minimax(tempGame, depth - 1, true, alpha, beta);
                minScore = min(minScore, score);
                beta = min(beta, score);
                // Alpha-Beta剪枝
                if (beta <= alpha)
                    break;
            }
        }
        return minScore;
    }
}

// 获取指定颜色的所有合法走法
vector<Move> HardAIStrategy::getAllValidMoves(const ChessGame &game, PieceColor color)
{
    vector<Move> moves;
    const auto &board = game.getBoard();

    for (int x = 0; x < BOARD_COLS; ++x)
    {
        for (int y = 0; y < BOARD_ROWS; ++y)
        {
            // 确保棋子存在且颜色匹配
            if (board[x][y] && board[x][y]->getPieceColor() == color)
            {
                for (int tx = 0; tx < BOARD_COLS; ++tx)
                {
                    for (int ty = 0; ty < BOARD_ROWS; ++ty)
                    {
                        // 确保不是原地移动
                        if ((tx != x || ty != y) &&
                            // 确保目标位置没有己方棋子
                            !(board[tx][ty] && board[tx][ty]->getPieceColor() == color) &&
                            // 确保移动是合法的
                            board[x][y]->canMoveTo(Point(tx, ty), board))
                        {
                            moves.emplace_back(Point(x, y), Point(tx, ty));
                        }
                    }
                }
            }
        }
    }

    return moves;
}